package com.tywj.buscustomerapp.view.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BusTravelBean;
import com.tywj.buscustomerapp.model.bean.StationBean;
import com.tywj.buscustomerapp.presenter.BasePresenter;
import com.tywj.buscustomerapp.presenter.MapPresenter;
import com.tywj.buscustomerapp.presenter.contract.MapContract;
import com.tywj.buscustomerapp.utils.DrivingRouteOverlay;
import com.tywj.buscustomerapp.utils.RecyclerItemClickListener;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.myadapter.CommonRcvAdapter;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.item.StationItem;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.TaylorImagWindow;
import com.tywj.buscustomerapp.view.myview.TaylorPopupWindowD;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MapActivity extends BaseActivityMvp implements MapContract.MapView{
    @BindView(R.id.head_left) ImageView back;
    @BindView(R.id.head_title) TextView title;
    @BindView(R.id.map) MapView mMapView;
    @BindView(R.id.map_recycler) RecyclerView recyclerView;
    @BindView(R.id.map_up) ImageView up;
    @BindView(R.id.framelayout) LinearLayout frameLayout;
    @BindView(R.id.line2) LinearLayout linearLayout;
    @BindView(R.id.travel_line_name) TextView travelLineName;
    @BindView(R.id.show_road) ImageView show_road;
    @BindView(R.id.start_location) ImageView start_location;
    @BindView(R.id.submit) TextView submit;
    @BindView(R.id.total_price) TextView total_price;
    @BindView(R.id.info_message) TextView info_message;

    private MapContract.MapPresenter presenter = new MapPresenter(this);
    private AMap map;
    private BusTravelBean.DataBean.ResultListBean travelLineBean=null;
    private List<StationBean> stations = new ArrayList<>();
    private List<StationBean> upStations = new ArrayList<>(2);//最终选择的出发起始站点
    private int height1 = 0;//获取的展开高度
    private int height2 = 0;//获取的闭合高度
    private CommonRcvAdapter<StationBean> adapter;
    private boolean isUp = true;//是否收缩
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private RouteSearch routeSearch ;
    private boolean isShowRound = false;//是否展示路况
    private Marker clickMarker = null;
    private LoadingDialog waitDialog;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_map;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 23) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            this.setTheme(R.style.AppTheme1);
        }
    }


    @Override
    public void initView() {
        title.setText("线路详情");
        back.setOnClickListener(this);
        up.setOnClickListener(this);
        show_road.setOnClickListener(this);
        start_location.setOnClickListener(this);
        submit.setOnClickListener(this);
        map = mMapView.getMap();
        if (map.getUiSettings()!=null) {
            map.getUiSettings().setZoomControlsEnabled(false);
        }
        copyFile();
        adapter = new CommonRcvAdapter<StationBean>(stations) {
            @NonNull
            @Override
            public AdapterItem createItem(Object type) {
                return new StationItem(stations.size());
            }
        };
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        if (getIntent()!=null){
            travelLineBean = (BusTravelBean.DataBean.ResultListBean) getIntent().getSerializableExtra("lineNum");
            if (travelLineBean!=null) {
                travelLineName.setText(travelLineBean.getXlqsz() + "—" + travelLineBean.getXlzdz());
                presenter.startLoadStations(travelLineBean.getXlbh());
                total_price.setText("￥"+travelLineBean.getXlpj());
                if (travelLineBean.getType().equals("CommuteLine")){
                    if (travelLineBean.getFcsj()!=null && Integer.valueOf(travelLineBean.getFcsj().substring(0,2))>12){
                        info_message.setVisibility(View.GONE);
                    }else{
                        info_message.setVisibility(View.VISIBLE);
                    }
                }else{
                    info_message.setVisibility(View.GONE);
                }
            }
        }
        startGetLocation();
        //显示定位点
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_my_lo);
        myLocationStyle.myLocationIcon(descriptor);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.transparent));
        myLocationStyle.strokeColor(getResources().getColor(R.color.transparent));
        myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        map.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        map.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }


    private void copyFile(){
        try {
            // 先获取系统默认的文档存放根目录
            File parent_path = Environment.getExternalStorageDirectory();
            File dir = new File(parent_path.getAbsoluteFile(), "com.tywj.buscustomerapp");
            if(!dir.exists()){
                dir.mkdir();
            }
            File file = new File(dir.getAbsoluteFile(), "style.data");
            if(file.exists()){
                map.setCustomMapStylePath(dir.getAbsolutePath()+"/style.data");
                map.setMapCustomEnable(true);
                return;
            }
            //读取数据文件getResources().openRawResource(R.raw.qq);
            InputStream open = this.getResources().openRawResource(R.raw.style);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while((len=open.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            map.setCustomMapStylePath(file.getAbsolutePath());
            map.setMapCustomEnable(true);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始路径规划
     */
    private void startRouteSearch() {
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                if (i== AMapException.CODE_AMAP_SUCCESS) {
                    if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                        final DrivePath drivePath = driveRouteResult.getPaths()
                                .get(0);
                        if(drivePath == null) {
                            return;
                        }
                        DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                                mContext, map, drivePath,
                                driveRouteResult.getStartPos(),
                                driveRouteResult.getTargetPos(), null,stations.get(0),stations.get(stations.size()-1));
                        drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                        drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                        drivingRouteOverlay.removeFromMap();
                        drivingRouteOverlay.addToMap();
                        drivingRouteOverlay.zoomToSpan();
                    }
                }else{
                    ToastJoe.getmToastJoe().ToastShow(MapActivity.this,null,"路径获取失败");
                }
                closeLoading();
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });
        LatLonPoint start = new LatLonPoint(upStations.get(0).getLat(),upStations.get(0).getLng());
        LatLonPoint end = new LatLonPoint(upStations.get(1).getLat(),upStations.get(1).getLng());
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(start,end);
        List<LatLonPoint> latLonPoints = new ArrayList<>();
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory//_99_pin_icon_pickup
                .decodeResource(getResources(),R.mipmap.jing)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        for (int i = 1; i < stations.size()-1; i++) {
            LatLonPoint point = new LatLonPoint(stations.get(i).getLat(), stations.get(i).getLng());
            latLonPoints.add(point);
            LatLng latLng = new LatLng(stations.get(i).getLat(), stations.get(i).getLng());
            markerOption.title(stations.get(i).getName());
//            markerOption.snippet(stations.get(i).getImg());
            markerOption.snippet("预计到达："+stations.get(i).getTime()+"？"+stations.get(i).getImg()+"？"+stations.get(i).getInfo());
            map.addMarker(markerOption.position(latLng));
        }
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,RouteSearch.DRIVING_MULTI_CHOICE_HIGHWAY_AVOID_CONGESTION, latLonPoints, null, "");
        routeSearch.calculateDriveRouteAsyn(query);
    }

    @Override
    public void initData() {
        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                for (int i = 0; i < stations.size(); i++) {
                    stations.get(i).isEnd = false;
                }
                stations.get(position).isEnd=true;
                upStations.set(1,stations.get(position));
                onShrink();
                LatLng latLng = new LatLng(stations.get(position).getLat(),stations.get(position).getLng());
                CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
                up.getCameraUpdateFactoryDelegate().zoom =18;
                map.animateCamera(up);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        }));
        map.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            View infoWindow = null;
            @Override
            public View getInfoWindow(Marker marker) {
                if(infoWindow == null) {
                    infoWindow = LayoutInflater.from(getApplicationContext()).inflate(
                            R.layout.map_infiwindow_layout, null);
                }
                render(marker, infoWindow);
                return infoWindow;
            }

            public void render(final Marker marker, View view) {
                TextView time = view.findViewById(R.id.time);
                TextView name = view.findViewById(R.id.name);
                TextView photo = view.findViewById(R.id.photo);
                TextView daohang = view.findViewById(R.id.daohang);
                String infos[] = marker.getSnippet().split("？");
                time.setText(infos[0]);
                name.setText(marker.getTitle());
                photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (marker.getTitle()!=null && !marker.getTitle().equals("")){
                            String path = marker.getSnippet().split("？")[1];
                            String info = marker.getSnippet().split("？")[2];
                            Log.i("taylor",path);
                            if (path!=null && !path.equals("") && !path.equals("null") && path.length()>0) {
                                TaylorImagWindow mPopwindow = new TaylorImagWindow(mContext, path,info);
                                mPopwindow.show();
                            }else{
                                ToastUtils.show("暂无站点图片");
                            }
                        }
                    }
                });
                daohang.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TaylorPopupWindowD popupWindow = new TaylorPopupWindowD(MapActivity.this,marker.getPosition());
                        popupWindow.showAtDropDownCenter(v);
                    }
                });
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        map.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {

            }
        });
        map.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getTitle()!=null && !marker.getTitle().equals("")){
                    clickMarker = marker;
                    clickMarker.showInfoWindow();
                }
                return true;
            }
        });
        map.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMarker!=null && clickMarker.isInfoWindowShown()){
                    clickMarker.hideInfoWindow();
                    clickMarker = null;
                }
            }
        });

    }


    @Override
    protected BasePresenter bindPresenter() {
        return presenter;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.head_left:
                finish();
                break;
            case R.id.map_up:
                if (isUp){
                    /**释放*/
                    onExpansion();
                }else{
                    /** 收缩*/
                    onShrink();
                }
                break;
            case R.id.show_road:
                //打开显示路况信息
                if (isShowRound){
                    show_road.setImageResource(R.mipmap.icon_traffic);
                }else{
                    show_road.setImageResource(R.mipmap.icon_traffic_pre);
                }
                map.setTrafficEnabled(!isShowRound);
                isShowRound = !isShowRound;
                break;
            case R.id.start_location:
                if (mLocationClient!=null)
                    mLocationClient.startLocation();
                break;
            case R.id.submit:
                String phone = SPUtils.getUserPhone(getApplicationContext());
                if (phone!=null && !phone.equals("")) {
                    Intent intent = new Intent(MapActivity.this, newBuyTicketActivity.class);
                    intent.putExtra("bus",travelLineBean);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(MapActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }



    @Override
    public void showMsg(String msg) {
        ToastJoe.getmToastJoe().ToastShow(MapActivity.this,null,msg+"");
    }

    @Override
    public void showLoading() {
        if (waitDialog==null)
            waitDialog = new LoadingDialog(MapActivity.this);
        if (!waitDialog.isShowing())
            waitDialog.show();
    }

    @Override
    public void closeLoading() {
        if (waitDialog!=null && waitDialog.isShowing())
            waitDialog.dismiss();
    }

    @Override
    public void loadedData(List<StationBean> s) {
        if (s!= null && s.size()>0){
            stations = s;
            stations.get(stations.size()-1).isEnd=true;
            upStations.add(stations.get(0));
            upStations.add(stations.get(stations.size()-1));
            adapter.setData(upStations);
            adapter.notifyDataSetChanged();
            startRouteSearch();

        }else{
            ToastJoe.getmToastJoe().ToastShow(this,null,"网络错误请重试");
        }
    }

    private void onExpansion(){
        height1 = recyclerView.getLayoutManager().getHeight();
        if (stations.size()>0 && height1!=0) {
            int endHeight = (height1/2) * stations.size();
            AniStart(height1,endHeight,isUp);
            adapter.setData(stations);
            adapter.notifyDataSetChanged();
            isUp = false;
            up.setImageResource(R.mipmap.icon_up);
        }
    }

    private void onShrink(){
        height2 = recyclerView.getLayoutManager().getHeight();
        if (upStations.size()==2 && height2!=0 && height1!=0) {
            AniStart(height2,height1,isUp);
            isUp = true;
            up.setImageResource(R.mipmap.icon_down);
        }
    }

    private void AniStart(int start, int end, final boolean is){
        ValueAnimator anim = ValueAnimator.ofInt(start, end);
        anim.setDuration(300);
        anim.setRepeatCount(0);//重复次数
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (Integer) animation.getAnimatedValue();
                recyclerView.getLayoutParams().height = currentValue;
                recyclerView.requestLayout();
            }
        });
        anim.start();
        anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (!is){
                    adapter.setData(upStations);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
            up.getCameraUpdateFactoryDelegate().zoom =18;
            map.animateCamera(up);
//            if (mylocationOptions==null) {
//                mylocationOptions = new MarkerOptions();
//                mylocationOptions.draggable(false);//设置Marker可拖动
//                mylocationOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                        .decodeResource(getResources(), R.mipmap.icon_my_lo)));
//                mylocationOptions.setFlat(true);//设置marker平贴地图效果
//            }else{
//                mylocationOptions.visible(false);
//                CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
//                up.getCameraUpdateFactoryDelegate().zoom =18;
//                map.animateCamera(up);
////                map.setMinZoomLevel(11);
//            }
//            map.addMarker(mylocationOptions.position(latLng));
        }
    };
    public void startGetLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationCacheEnable(false);//关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        MobclickAgent.onPageStart("线路详情");
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
        MobclickAgent.onPageEnd("线路详情");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView!=null)
            mMapView.onDestroy();
    }


}
